{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Minibatch Stochastic Gradient Descent\n",
    ":label:`sec_minibatch_sgd`\n",
    "\n",
    "So far we encountered two extremes in the approach to gradient based learning: :numref:`sec_gd` uses the full dataset to compute gradients and to update parameters, one pass at a time. Conversely :numref:`sec_sgd` processes one observation at a time to make progress. Each of them has its own drawbacks. Gradient Descent is not particularly *data efficient* whenever data is very similar. Stochastic Gradient Descent is not particularly *computationally efficient* since CPUs and GPUs cannot exploit the full power of vectorization. This suggests that there might be a happy medium, and in fact, that's what we have been using so far in the examples we discussed. \n",
    "\n",
    "## Vectorization and Caches\n",
    "\n",
    "At the heart of the decision to use minibatches is computational efficiency. This is most easily understood when considering parallelization to multiple GPUs and multiple servers. In this case we need to send at least one image to each GPU. With 8 GPUs per server and 16 servers we already arrive at a minibatch size of 128.\n",
    "\n",
    "Things are a bit more subtle when it comes to single GPUs or even CPUs. These devices have multiple types of memory, often multiple type of compute units and different bandwidth constraints between them. For instance, a CPU has a small number of registers and then L1, L2 and in some cases even L3 cache (which is shared between the different processor cores). These caches are of increasing size and latency (and at the same time they are of decreasing bandwidth). Suffice it to say, the processor is capable of performing many more operations than what the main memory interface is able to provide. \n",
    "\n",
    "* A 2GHz CPU with 16 cores and AVX-512 vectorization can process up to $2 \\cdot 10^9 \\cdot 16 \\cdot 32 = 10^{12}$ bytes per second. The capability of GPUs easily exceeds this number by a factor of 100. On the other hand, a midrange server processor might not have much more than 100 GB/s bandwidth, i.e., less than one tenth of what would be required to keep the processor fed. To make matters worse, not all memory access is created equal: first, memory interfaces are typically 64 bit wide or wider (e.g., on GPUs up to 384 bit), hence reading a single byte incurs the cost of a much wider access. \n",
    "* There is significant overhead for the first access whereas sequential access is relatively cheap (this is often called a burst read). There are many more things to keep in mind, such as caching when we have multiple sockets, chiplets and other structures. A detailed discussion of this is beyond the scope of this section. See e.g., this [Wikipedia article](https://en.wikipedia.org/wiki/Cache_hierarchy) for a more in-depth discussion.\n",
    "\n",
    "The way to alleviate these constraints is to use a hierarchy of CPU caches which are actually fast enough to supply the processor with data. This is *the* driving force behind batching in deep learning. To keep matters simple, consider matrix-matrix multiplication, say $\\mathbf{A} = \\mathbf{B}\\mathbf{C}$. We have a number of options for calculating $\\mathbf{A}$. For instance we could try the following:\n",
    "\n",
    "1. We could compute $\\mathbf{A}_{ij} = \\mathbf{B}_{i,:} \\mathbf{C}_{:,j}^\\top$, i.e., we could compute it element-wise by means of dot products.\n",
    "1. We could compute $\\mathbf{A}_{:,j} = \\mathbf{B} \\mathbf{C}_{:,j}^\\top$, i.e., we could compute it one column at a time. Likewise we could compute $\\mathbf{A}$ one row $\\mathbf{A}_{i,:}$ at a time. \n",
    "1. We could simply compute $\\mathbf{A} = \\mathbf{B} \\mathbf{C}$. \n",
    "1. We could break $\\mathbf{B}$ and $\\mathbf{C}$ into smaller block matrices and compute $\\mathbf{A}$ one block at a time. \n",
    "\n",
    "If we follow the first option, we will need to copy one row and one column vector into the CPU each time we want to compute an element $\\mathbf{A}_{ij}$. Even worse, due to the fact that matrix elements are aligned sequentially we are thus required to access many disjoint locations for one of the two vectors as we read them from memory. The second option is much more favorable. In it, we are able to keep the column vector $\\mathbf{C}_{:,j}$ in the CPU cache while we keep on traversing through $B$. This halves the memory bandwidth requirement with correspondingly faster access. Of course, option 3 is most desirable. Unfortunately, most matrices might not entirely fit into cache (this is what we are discussing after all). However, option 4 offers a practically useful alternative: we can move blocks of the matrix into cache and multiply them locally. Optimized libraries take care of this for us. Let us have a look at how efficient these operations are in practice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/Accumulator.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.basicdataset.tabular.*;\n",
    "import ai.djl.basicdataset.cv.classification.*;\n",
    "import org.apache.commons.lang3.ArrayUtils;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "StopWatch stopWatch = new StopWatch();\n",
    "NDArray A = manager.zeros(new Shape(256, 256));\n",
    "NDArray B = manager.randomNormal(new Shape(256, 256));\n",
    "NDArray C = manager.randomNormal(new Shape(256, 256));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Element-wise assignment simply iterates over all rows and columns of $\\mathbf{B}$ and $\\mathbf{C}$ respectively to assign the value to $\\mathbf{A}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// Compute A = B C one element at a time\n",
    "stopWatch.start();\n",
    "for (int i = 0; i < 256; i++) {\n",
    "    for (int j = 0; j < 256; j++) {\n",
    "        A.set(new NDIndex(i, j), \n",
    "              B.get(new NDIndex(String.format(\"%d, :\", i)))\n",
    "              .dot(C.get(new NDIndex(String.format(\":, %d\", j)))));\n",
    "    }\n",
    "}\n",
    "stopWatch.stop();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A faster strategy is to perform column-wise assignment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// Compute A = B C one column at a time\n",
    "stopWatch.start();\n",
    "for (int j = 0; j < 256; j++) {\n",
    "    A.set(new NDIndex(String.format(\":, %d\", j)), B.dot(C.get(new NDIndex(String.format(\":, %d\", j)))));\n",
    "}\n",
    "stopWatch.stop();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Last, the most effective manner is to perform the entire operation in one block. Let us see what the respective speed of the operations is."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// Compute A = B C in one go\n",
    "stopWatch.start();\n",
    "A = B.dot(C);\n",
    "stopWatch.stop();\n",
    "\n",
    "// Multiply and add count as separate operations (fused in practice)\n",
    "float[] gigaflops = new float[stopWatch.getTimes().size()];\n",
    "for (int i = 0; i < stopWatch.getTimes().size(); i++) {\n",
    "    gigaflops[i] = (float)(2 / stopWatch.getTimes().get(i));\n",
    "}\n",
    "String.format(\"Performance in Gigaflops: element %.3f, column %.3f, full %.3f\", gigaflops[0], gigaflops[1], gigaflops[2]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Minibatches \n",
    "\n",
    ":label:`sec_minibatches`\n",
    "\n",
    "In the past we took it for granted that we would read *minibatches* of data rather than single observations to update parameters. We now give a brief justification for it. Processing single observations requires us to perform many single matrix-vector (or even vector-vector) multiplications, which is quite expensive and which incurs a significant overhead on behalf of the underlying deep learning framework. This applies both to evaluating a network when applied to data (often referred to as inference) and when computing gradients to update parameters. That is, this applies whenever we perform $\\mathbf{w} \\leftarrow \\mathbf{w} - \\eta_t \\mathbf{g}_t$ where \n",
    "\n",
    "$$\\mathbf{g}_t = \\partial_{\\mathbf{w}} f(\\mathbf{x}_{t}, \\mathbf{w})$$\n",
    "\n",
    "We can increase the *computational* efficiency of this operation by applying it to a minibatch of observations at a time. That is, we replace the gradient $\\mathbf{g}_t$ over a single observation by one over a small batch\n",
    "\n",
    "$$\\mathbf{g}_t = \\partial_{\\mathbf{w}} \\frac{1}{|\\mathcal{B}_t|} \\sum_{i \\in \\mathcal{B}_t} f(\\mathbf{x}_{i}, \\mathbf{w})$$\n",
    "\n",
    "Let us see what this does to the statistical properties of $\\mathbf{g}_t$: since both $\\mathbf{x}_t$ and also all elements of the minibatch $\\mathcal{B}_t$ are drawn uniformly at random from the training set, the expectation of the gradient remains unchanged. The variance, on the other hand, is reduced significantly. Since the minibatch gradient is composed of $b := |\\mathcal{B}_t|$ independent gradients which are being averaged, its standard deviation is reduced by a factor of $b^{-\\frac{1}{2}}$. This, by itself, is a good thing, since it means that the updates are more reliably aligned with the full gradient. \n",
    "\n",
    "Naively this would indicate that choosing a large minibatch $\\mathcal{B}_t$ would be universally desirable. Alas, after some point, the additional reduction in standard deviation is minimal when compared to the linear increase in computational cost. In practice we pick a minibatch that is large enough to offer good computational efficiency while still fitting into the memory of a GPU. To illustrate the savings let us have a look at some code. In it we perform the same matrix-matrix multiplication, but this time broken up into \"minibatches\" of 64 columns at a time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stopWatch.start();\n",
    "for (int j = 0; j < 256; j+=64) {\n",
    "    A.set(new NDIndex(String.format(\":, %d:%d\", j, j + 64)), \n",
    "        B.dot(C.get(new NDIndex(String.format(\":, %d:%d\", j, j + 64)))));\n",
    "}\n",
    "stopWatch.stop();\n",
    "\n",
    "String.format(\"Performance in Gigaflops: block %.3f\\n\", 2 / stopWatch.getTimes().get(3));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, the computation on the minibatch is essentially as efficient as on the full matrix. A word of caution is in order. In :numref:`sec_batch_norm` we used a type of regularization that was heavily dependent on the amount of variance in a minibatch. As we increase the latter, the variance decreases and with it the benefit of the noise-injection due to batch normalization. See e.g., :cite:`Ioffe.2017` for details on how to rescale and compute the appropriate terms. \n",
    "\n",
    "## Reading the Dataset\n",
    "\n",
    "Let us have a look at how minibatches are efficiently generated from data. In the following we use a dataset developed by NASA to test the wing [noise from different aircraft](https://archive.ics.uci.edu/ml/datasets/Airfoil+Self-Noise) to compare these optimization algorithms. For convenience we only use the first $1,500$ examples. The data is whitened for preprocessing, i.e., we remove the mean and rescale the variance to $1$ per coordinate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "\n",
    "public AirfoilRandomAccess getDataCh11(int batchSize, int n) throws IOException, TranslateException {\n",
    "    // Load data\n",
    "    AirfoilRandomAccess airfoil = AirfoilRandomAccess.builder()\n",
    "            .optUsage(Dataset.Usage.TRAIN)\n",
    "            .setSampling(batchSize, true)\n",
    "            .optNormalize(true)\n",
    "            .optLimit(n)\n",
    "            .build();\n",
    "    return airfoil;\n",
    "}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Implementation from Scratch\n",
    "\n",
    "Recall the minibatch SGD implementation from :numref:`sec_linear_scratch`. In the following we provide a slightly more general implementation. For convenience it has the same call signature as the other optimization algorithms introduced later in this chapter. Specifically, we add the status\n",
    "input `states` and place the hyperparameter in dictionary `hyperparams`. In\n",
    "addition, we will average the loss of each minibatch example in the training\n",
    "function, so the gradient in the optimization algorithm does not need to be\n",
    "divided by the batch size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public class Optimization {\n",
    "    public static void sgd(NDList params, NDList states, Map<String, Float> hyperparams) {\n",
    "        for (int i = 0; i < params.size(); i++) {\n",
    "            NDArray param = params.get(i);\n",
    "            // Update param\n",
    "            // param = param - param.gradient * lr\n",
    "            param.subi(param.getGradient().mul(hyperparams.get(\"lr\")));\n",
    "        }\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we implement a generic training function to facilitate the use of the other optimization algorithms introduced later in this chapter. It initializes a linear regression model and can be used to train the model with minibatch SGD and other algorithms introduced subsequently."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static float evaluateLoss(Iterable<Batch> dataIterator, NDArray w, NDArray b) {\n",
    "    Accumulator metric = new Accumulator(2);  // sumLoss, numExamples\n",
    "\n",
    "    for (Batch batch : dataIterator) {\n",
    "        NDArray X = batch.getData().head();\n",
    "        NDArray y = batch.getLabels().head();\n",
    "        NDArray yHat = Training.linreg(X, w, b);\n",
    "        float lossSum = Training.squaredLoss(yHat, y).sum().getFloat();\n",
    "\n",
    "        metric.add(new float[]{lossSum, (float) y.size()});\n",
    "        batch.close();\n",
    "    }\n",
    "    return metric.get(0) / metric.get(1);\n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static class LossTime {\n",
    "    public float[] loss;\n",
    "    public float[] time;\n",
    "\n",
    "    public LossTime(float[] loss, float[] time) {\n",
    "        this.loss = loss;\n",
    "        this.time = time;\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public void plotLossEpoch(float[] loss, float[] epoch) {\n",
    "    Table data = Table.create(\"data\")\n",
    "        .addColumns(\n",
    "            DoubleColumn.create(\"epoch\", Functions.floatToDoubleArray(epoch)),\n",
    "            DoubleColumn.create(\"loss\", Functions.floatToDoubleArray(loss))\n",
    "    );\n",
    "    display(LinePlot.create(\"loss vs. epoch\", data, \"epoch\", \"loss\"));\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public float[] arrayListToFloat (ArrayList<Double> arrayList) {\n",
    "    float[] ret = new float[arrayList.size()];\n",
    "    \n",
    "    for (int i = 0; i < arrayList.size(); i++) {\n",
    "        ret[i] = arrayList.get(i).floatValue();\n",
    "    }\n",
    "    return ret;\n",
    "}\n",
    "\n",
    "@FunctionalInterface\n",
    "public static interface TrainerConsumer {\n",
    "    void train(NDList params, NDList states, Map<String, Float> hyperparams);\n",
    "\n",
    "}\n",
    "\n",
    "public static LossTime trainCh11(TrainerConsumer trainer, NDList states, Map<String, Float> hyperparams,\n",
    "                                AirfoilRandomAccess dataset,\n",
    "                                int featureDim, int numEpochs) throws IOException, TranslateException {\n",
    "    NDManager manager = NDManager.newBaseManager();\n",
    "    NDArray w = manager.randomNormal(0, 0.01f, new Shape(featureDim, 1), DataType.FLOAT32);\n",
    "    NDArray b = manager.zeros(new Shape(1));\n",
    "\n",
    "    w.setRequiresGradient(true);\n",
    "    b.setRequiresGradient(true);\n",
    "\n",
    "    NDList params = new NDList(w, b);\n",
    "    int n = 0;\n",
    "    StopWatch stopWatch = new StopWatch();\n",
    "    stopWatch.start();\n",
    "\n",
    "    float lastLoss = -1;\n",
    "    ArrayList<Double> loss = new ArrayList<>();\n",
    "    ArrayList<Double> epoch = new ArrayList<>();\n",
    "    \n",
    "    for (int i = 0; i < numEpochs; i++) {\n",
    "        for (Batch batch : dataset.getData(manager)) {\n",
    "            int len = (int) dataset.size() / batch.getSize();  // number of batches\n",
    "            NDArray X = batch.getData().head();\n",
    "            NDArray y = batch.getLabels().head();\n",
    "\n",
    "            NDArray l;\n",
    "            try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {\n",
    "                NDArray yHat = Training.linreg(X, params.get(0), params.get(1));\n",
    "                l = Training.squaredLoss(yHat, y).mean();\n",
    "                gc.backward(l);\n",
    "            }\n",
    "\n",
    "            trainer.train(params, states, hyperparams);\n",
    "            n += X.getShape().get(0);\n",
    "\n",
    "            if (n % 200 == 0) {\n",
    "                stopWatch.stop();\n",
    "                lastLoss = evaluateLoss(dataset.getData(manager), params.get(0), params.get(1));\n",
    "                loss.add((double) lastLoss);\n",
    "                double lastEpoch = 1.0 * n / X.getShape().get(0) / len;\n",
    "                epoch.add(lastEpoch);\n",
    "                stopWatch.start();\n",
    "            }\n",
    "\n",
    "            batch.close();\n",
    "        }\n",
    "    }\n",
    "    float[] lossArray = arrayListToFloat(loss);\n",
    "    float[] epochArray = arrayListToFloat(epoch);\n",
    "    plotLossEpoch(lossArray, epochArray);\n",
    "    System.out.printf(\"loss: %.3f, %.3f sec/epoch\\n\", lastLoss, stopWatch.avg());\n",
    "    float[] timeArray = arrayListToFloat(stopWatch.cumsum());\n",
    "    return new LossTime(lossArray, timeArray);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us see how optimization proceeds for batch gradient descent. This can be achieved by setting the minibatch size to 1500 (i.e., to the total number of examples). As a result the model parameters are updated only once per epoch. There is little progress. In fact, after 6 steps progress stalls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static LossTime trainSgd(float lr, int batchSize, int numEpochs) throws IOException, TranslateException {\n",
    "    AirfoilRandomAccess dataset = getDataCh11(batchSize, 1500);\n",
    "    int featureDim = dataset.getColumnNames().size();\n",
    "\n",
    "    Map<String, Float> hyperparams = new HashMap<>();\n",
    "    hyperparams.put(\"lr\", lr);\n",
    "\n",
    "    return trainCh11(Optimization::sgd, new NDList(), hyperparams, dataset, featureDim, numEpochs);\n",
    "}\n",
    "\n",
    "LossTime gdRes = trainSgd(1f, 1500, 10);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When the batch size equals 1, we use SGD for optimization. For simplicity of implementation we picked a constant (albeit small) learning rate. In SGD, the model parameters are updated whenever an example is processed. In our case this amounts to 1500 updates per epoch. As we can see, the decline in the value of the objective function slows down after one epoch. Although both the procedures processed 1500 examples within one epoch, SGD consumes more time than gradient descent in our experiment. This is because SGD updated the parameters more frequently and since it is less efficient to process single observations one at a time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "LossTime sgdRes = trainSgd(0.005f, 1, 2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Last, when the batch size equals 100, we use minibatch SGD for optimization. The time required per epoch is longer than the time needed for SGD and the time for batch gradient descent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "LossTime mini1Res = trainSgd(0.4f, 100, 2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reducing the batch size to 10, the time for each epoch increases because the workload for each batch is less efficient to execute."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "LossTime mini2Res = trainSgd(0.05f, 10, 2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we compare the time versus loss for the preview four experiments. As can be seen, despite SGD converges faster than GD in terms of number of examples processed, it uses more time to reach the same loss than GD because that computing gradient example by example is not efficient. Minibatch SGD is able to trade-off the convergence speed and computation efficiency. A minibatch size 10 is more efficient than SGD; a minibatch size 100 even outperforms GD in terms of runtime."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public String[] getTypeArray(LossTime lossTime, String name) {\n",
    "    String[] type = new String[lossTime.time.length];\n",
    "    for (int i = 0; i < type.length; i++) {\n",
    "        type[i] = name;\n",
    "    }\n",
    "    return type;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// Converts a float array to a log scale\n",
    "float[] convertLogScale(float[] array) {\n",
    "    float[] newArray = new float[array.length];\n",
    "    for (int i = 0; i < array.length; i++) {\n",
    "        newArray[i] = (float) Math.log10(array[i]);\n",
    "    }\n",
    "    return newArray;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float[] time = ArrayUtils.addAll(ArrayUtils.addAll(gdRes.time, sgdRes.time), \n",
    "                                 ArrayUtils.addAll(mini1Res.time, mini2Res.time));\n",
    "float[] loss = ArrayUtils.addAll(ArrayUtils.addAll(gdRes.loss, sgdRes.loss), \n",
    "                                 ArrayUtils.addAll(mini1Res.loss, mini2Res.loss));\n",
    "String[] type = ArrayUtils.addAll(ArrayUtils.addAll(getTypeArray(gdRes, \"gd\"), \n",
    "                                                    getTypeArray(sgdRes, \"sgd\")), \n",
    "                                  ArrayUtils.addAll(getTypeArray(mini1Res, \"batch size = 100\"), \n",
    "                                  getTypeArray(mini1Res, \"batch size = 10\")));\n",
    "Table data = Table.create(\"data\")\n",
    "    .addColumns(\n",
    "        DoubleColumn.create(\"log time (sec)\", Functions.floatToDoubleArray(convertLogScale(time))),\n",
    "        DoubleColumn.create(\"loss\", Functions.floatToDoubleArray(loss)),\n",
    "        StringColumn.create(\"type\", type)\n",
    "    );\n",
    "LinePlot.create(\"loss vs. time\", data, \"log time (sec)\", \"loss\", \"type\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Concise Implementation\n",
    "\n",
    "In DJL, we can use the `Optimizer` package to access different optimization algorithms. This is used to implement a generic training function. We will use this throughout the current chapter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public void trainConciseCh11(Optimizer sgd, AirfoilRandomAccess dataset, \n",
    "                            int numEpochs) throws IOException, TranslateException {\n",
    "    // Initialization\n",
    "    NDManager manager = NDManager.newBaseManager();\n",
    "\n",
    "    SequentialBlock net = new SequentialBlock();\n",
    "    Linear linear = Linear.builder().setUnits(1).build();\n",
    "    net.add(linear);\n",
    "    net.setInitializer(new NormalInitializer(), Parameter.Type.WEIGHT);\n",
    "\n",
    "    Model model = Model.newInstance(\"concise implementation\");\n",
    "    model.setBlock(net);\n",
    "\n",
    "    Loss loss = Loss.l2Loss();\n",
    "\n",
    "    DefaultTrainingConfig config = new DefaultTrainingConfig(loss)\n",
    "        .optOptimizer(sgd)\n",
    "        .addEvaluator(new Accuracy()) // Model Accuracy\n",
    "        .addTrainingListeners(TrainingListener.Defaults.logging()); // Logging\n",
    "\n",
    "    Trainer trainer = model.newTrainer(config);\n",
    "\n",
    "    int n = 0;\n",
    "    StopWatch stopWatch = new StopWatch();\n",
    "    stopWatch.start();\n",
    "\n",
    "    trainer.initialize(new Shape(10, 5));\n",
    "\n",
    "    Metrics metrics = new Metrics();\n",
    "    trainer.setMetrics(metrics);\n",
    "\n",
    "    float lastLoss = -1;\n",
    "    \n",
    "    ArrayList<Double> lossArray = new ArrayList<>();\n",
    "    ArrayList<Double> epochArray = new ArrayList<>();\n",
    "    \n",
    "    for (Batch batch : trainer.iterateDataset(dataset)) {\n",
    "        int len = (int) dataset.size() / batch.getSize();  // number of batches\n",
    "\n",
    "        NDArray X = batch.getData().head();\n",
    "        EasyTrain.trainBatch(trainer, batch);\n",
    "        trainer.step();\n",
    "        \n",
    "        n += X.getShape().get(0);\n",
    "        \n",
    "        if (n % 200 == 0) {\n",
    "            stopWatch.stop();\n",
    "            stopWatch.stop();\n",
    "            lastLoss = evaluateLoss(dataset.getData(manager), linear.getParameters().get(0).getValue().getArray()\n",
    "                            .reshape(new Shape(dataset.getColumnNames().size(), 1)),\n",
    "                    linear.getParameters().get(1).getValue().getArray());\n",
    "            \n",
    "            lossArray.add((double) lastLoss);\n",
    "            double lastEpoch = 1.0 * n / X.getShape().get(0) / len;\n",
    "            epochArray.add(lastEpoch);\n",
    "            stopWatch.start();\n",
    "        }\n",
    "        batch.close();\n",
    "    }\n",
    "    plotLossEpoch(arrayListToFloat(lossArray), arrayListToFloat(epochArray));\n",
    "\n",
    "    System.out.printf(\"loss: %.3f, %.3f sec/epoch\\n\", lastLoss, stopWatch.avg());\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using DJL to repeat the last experiment shows identical behavior."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "AirfoilRandomAccess airfoilDataset = getDataCh11(10, 1500);\n",
    "\n",
    "Tracker lrt = Tracker.fixed(0.05f);\n",
    "Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build();\n",
    "\n",
    "trainConciseCh11(sgd, airfoilDataset, 2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "* Vectorization makes code more efficient due to reduced overhead arising from the deep learning framework and due to better memory locality and caching on CPUs and GPUs. \n",
    "* There is a trade-off between statistical efficiency arising from SGD and computational efficiency arising from processing large batches of data at a time. \n",
    "* Minibatch stochastic gradient descent offers the best of both worlds: computational and statistical efficiency. \n",
    "* In minibatch SGD we process batches of data obtained by a random permutation of the training data (i.e., each observation is processed only once per epoch, albeit in random order). \n",
    "* It is advisable to decay the learning rates during training. \n",
    "* In general, minibatch SGD is faster than SGD and gradient descent for convergence to a smaller risk, when measured in terms of clock time.  \n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Modify the batch size and learning rate and observe the rate of decline for the value of the objective function and the time consumed in each epoch.\n",
    "1. Read the DJL documentation and explore the different learning rate trackers in `ai.djl.training.optimizer.tracker` to see how they affect training. Try using a `FactorTracker` to reduce the learning rate to 1/10 of its previous value after each epoch.\n",
    "1. Compare minibatch SGD with a variant that actually *samples with replacement* from the training set. What happens?\n",
    "1. An evil genie replicates your dataset without telling you (i.e., each observation occurs twice and your dataset grows to twice its original size, but nobody told you). How does the behavior of SGD, minibatch SGD and that of gradient descent change?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
